package com.budwk.app.sqfwV2.generator.weiqingmen;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CommonParam;
import com.budwk.app.sqfwV2.dto.weiqingmen.*;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.util.poiUtils.PictureUtils;
import com.google.common.collect.Maps;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @BelongsProject: dfxy-shequ
 * @Author: yangweimin
 * @CreateTime: 2024-04-02  09:59
 * @Description: TODO
 */
public class BaseGenerator {

    private static final String UNIT_NAME = "威清门街道直属";

    public static final Map<String, Object> HIDDEN_MAP = new HashMap<>();

    static {
        HIDDEN_MAP.put("无", "");
        HIDDEN_MAP.put("经排查暂无隐患", "");
        HIDDEN_MAP.put("暂未发现隐患", "");
        HIDDEN_MAP.put("未发现安全隐患", "");
        HIDDEN_MAP.put("暂未发现问题", "");
        HIDDEN_MAP.put("暂无发现问题", "");
        HIDDEN_MAP.put("经排查暂无发现隐患", "");
        HIDDEN_MAP.put("只配备灭火器暂未发现安全隐患", "");
        HIDDEN_MAP.put("经排查暂无隐患该经营户使用诚纳源和醇基燃料", "");
        HIDDEN_MAP.put("经排查电线穿管配备灭火器暂无隐患", "");
    }

    public static String getHidden(String str) {
        if (StringUtils.isBlank(str) || HIDDEN_MAP.containsKey(str)) return "无";
        return str;
    }

    /**
     * 设置巡查内容状态
     * @param paramMap
     * @param arrayOfFireSafetyPatrolRecords
     */
    public static void setArrayOfFireSafetyPatrolRecords(Map<String, Object> paramMap, List<RectifyDTO> arrayOfFireSafetyPatrolRecords) {
        // 存在问题数量
        int problem = 0;
        // 是否存在问题数组
        List<Boolean> isProblems = new ArrayList<>();

        for (RectifyDTO rectifyDTO : arrayOfFireSafetyPatrolRecords) {
            if (StringUtils.isNotBlank(rectifyDTO.getRectificationDate()) && !"已整改".equals(rectifyDTO.getRectificationDate())) {
                problem ++;
                isProblems.add(true);
            } else {
                isProblems.add(false);
            }
        }
        paramMap.put("arrayOfFireSafetyPatrolRecords", isProblems);
        paramMap.put("problem", problem);
    }

    /**
     * 瓶装燃气用户安全管理检查表
     * @param paramMap
     * @param bottledGasProblemArray
     */
    public static void setBottledGasProblemArray(Map<String, Object> paramMap, List<RectifyDTO> bottledGasProblemArray) {
        // 存在问题数量
        int problem = 0;
        // 是否存在问题数组
        List<String> isProblems = new ArrayList<>();

        for (RectifyDTO rectifyDTO : bottledGasProblemArray) {
            if (StringUtils.isNotBlank(rectifyDTO.getRectificationDate()) && !"已整改".equals(rectifyDTO.getRectificationDate())) {
                problem ++;
                isProblems.add("否");
            } else {
                isProblems.add("是");
            }
        }
        paramMap.put("bottledGasProblemArray", isProblems);
        paramMap.put("problem", problem);
    }

    /**
     * 获取已整改问题编号
     * @param arrayOfFireSafetyPatrolRecords
     * @return
     */
    public static List<String> getChangeNum(List<RectifyDTO> arrayOfFireSafetyPatrolRecords) {
        // 限期整改问题编号
        List<String> list = new ArrayList<>();

        int i = 1;
        for (RectifyDTO rectifyDTO : arrayOfFireSafetyPatrolRecords) {
            if ("已整改".equals(rectifyDTO.getRectificationDate())) {
                list.add(i + "");
            }
            i ++;
        }
        return list;
    }

    /**
     * 获取现场整改问题编号
     * @param arrayOfFireSafetyPatrolRecords
     * @return
     */
    public static List<String> getSceneChangeNum(List<RectifyDTO> arrayOfFireSafetyPatrolRecords) {
        // 限期整改问题编号
        List<String> list = new ArrayList<>();

        int i = 1;
        for (RectifyDTO rectifyDTO : arrayOfFireSafetyPatrolRecords) {
            if ("现场整改".equals(rectifyDTO.getRectificationDate())) {
                list.add(i + "");
            }
            i ++;
        }
        return list;
    }

    /**
     * 获取限期整改问题编号
     * @param arrayOfFireSafetyPatrolRecords
     * @return
     */
    public static List<String> getDeadlineChangeNum(List<RectifyDTO> arrayOfFireSafetyPatrolRecords) {
        // 限期整改问题编号
        List<String> list = new ArrayList<>();

        int i = 1;
        for (RectifyDTO rectifyDTO : arrayOfFireSafetyPatrolRecords) {
            if ("限期整改".equals(rectifyDTO.getRectificationDate())) {
                list.add(i + "");
            }
            i ++;
        }

        return list;
    }

    /**
     * 获取巡查发现的隐患问题，包含现场整改和限期整改问题
     * @param fieldDTO
     * @param rectificationDates 整改类型筛选（有些情况只要 限期整改 的问题）
     * @return
     */
    public static String getHiddenDangers(SafetyCheckDTO fieldDTO, String ... rectificationDates) {
        StringBuilder stringBuilder = new StringBuilder();
        Integer num = 1;

        List<RectifyDTO> recordsDTO = Optional.ofNullable(fieldDTO.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
        List<RectifyDTO> bottledDTO = Optional.ofNullable(fieldDTO.getBottledGasProblemArray()).orElse(Lists.newArrayList());
        OtherHiddenDangersDTO otherDTO = fieldDTO.getOtherHiddenDangers();

        String rectificationDate = rectificationDates.length > 0 ? rectificationDates[0] : null;
        String other = rectificationDates.length > 1 ? rectificationDates[1] : null;

        // 消防安全隐患
        for (RectifyDTO rectifyDTO : recordsDTO) {
            if ("已整改".equals(rectifyDTO.getRectificationDate())) continue;

            if (rectificationDate == null && StringUtils.isNotBlank(rectifyDTO.getRectificationDate())) {
                stringBuilder.append(num).append("、").append(rectifyDTO.getTitle()).append("  ");
                num ++;
            }
            if (rectificationDate != null && rectificationDate.equals(rectifyDTO.getRectificationDate())) {
                stringBuilder.append(num).append("、").append(rectifyDTO.getTitle()).append("  ");
                num ++;
            }
        }

        // 瓶装燃气隐患
        int i = 0;
        for (RectifyDTO rectifyDTO : bottledDTO) {

            // 重复问题不显示
            i ++;
            if (notShow(i)) continue;

            if ("已整改".equals(rectifyDTO.getRectificationDate())) continue;

            if (rectificationDate == null && StringUtils.isNotBlank(rectifyDTO.getRectificationDate())) {
                stringBuilder.append(num).append("、").append(rectifyDTO.getTitle()).append("  ");
                num ++;
            }
            if (rectificationDate != null && rectificationDate.equals(rectifyDTO.getRectificationDate())) {
                stringBuilder.append(num).append("、").append(rectifyDTO.getTitle()).append("  ");
                num ++;
            }
        }

        // 其他隐患
        if (!"notOther".equals(other) && otherDTO != null && StringUtils.isNotBlank(otherDTO.getKey()) && !HIDDEN_MAP.containsKey(otherDTO.getKey())) {
            stringBuilder.append(num).append("、").append(otherDTO.getKey());
        }

        return stringBuilder.length() == 0 ? "无" : stringBuilder.toString();
    }

    /**
     * 获取巡查发现的隐患问题，包含现场整改和限期整改问题(不统计其他问题)
     * @param fieldDTO
     * @param rectificationDates 整改类型筛选（有些情况只要 限期整改 的问题）
     * @return
     */
    public static String getHiddenNotOther(SafetyCheckDTO fieldDTO, String ... rectificationDates) {
        StringBuilder stringBuilder = new StringBuilder();
        Integer num = 1;

        List<RectifyDTO> recordsDTO = Optional.ofNullable(fieldDTO.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
        List<RectifyDTO> bottledDTO = Optional.ofNullable(fieldDTO.getBottledGasProblemArray()).orElse(Lists.newArrayList());
        OtherHiddenDangersDTO otherDTO = fieldDTO.getOtherHiddenDangers();

        String rectificationDate = rectificationDates.length > 0 ? rectificationDates[0] : null;
        String other = rectificationDates.length > 1 ? rectificationDates[1] : null;

        // 消防安全隐患
        for (RectifyDTO rectifyDTO : recordsDTO) {
            if ("已整改".equals(rectifyDTO.getRectificationDate())) continue;

            if (rectificationDate == null && StringUtils.isNotBlank(rectifyDTO.getRectificationDate())) {
                stringBuilder.append(num).append("、").append(rectifyDTO.getTitle()).append("  ");
                num ++;
            }
            if (rectificationDate != null && rectificationDate.equals(rectifyDTO.getRectificationDate())) {
                stringBuilder.append(num).append("、").append(rectifyDTO.getTitle()).append("  ");
                num ++;
            }
        }

        // 瓶装燃气隐患
        int i = 0;
        for (RectifyDTO rectifyDTO : bottledDTO) {

            // 重复问题不显示
            i ++;
            if (notShow(i)) continue;

            if ("已整改".equals(rectifyDTO.getRectificationDate())) continue;

            if (rectificationDate == null && StringUtils.isNotBlank(rectifyDTO.getRectificationDate())) {
                stringBuilder.append(num).append("、").append(rectifyDTO.getTitle()).append("  ");
                num ++;
            }
            if (rectificationDate != null && rectificationDate.equals(rectifyDTO.getRectificationDate())) {
                stringBuilder.append(num).append("、").append(rectifyDTO.getTitle()).append("  ");
                num ++;
            }
        }
        return stringBuilder.length() == 0 ? "无" : stringBuilder.toString();
    }

    /**
     * 获取整改措施
     * @param fieldDTO
     * @return
     */
    public static String getMeasure(SafetyCheckDTO fieldDTO) {
        List<RectifyDTO> recordsDTO = Optional.ofNullable(fieldDTO.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
        List<RectifyDTO> bottledDTO = Optional.ofNullable(fieldDTO.getBottledGasProblemArray()).orElse(Lists.newArrayList());
        OtherHiddenDangersDTO otherDTO = fieldDTO.getOtherHiddenDangers();

        // 消防安全隐患
        for (RectifyDTO rectifyDTO : recordsDTO) {
            if ("限期整改".equals(rectifyDTO.getRectificationDate())) {
                return "督促在规定时间内整改";
            }
        }

        // 瓶装燃气隐患
        int i = 0;
        for (RectifyDTO rectifyDTO : bottledDTO) {

            // 重复问题不显示
            i ++;
            if (notShow(i)) continue;

            if ("限期整改".equals(rectifyDTO.getRectificationDate())) {
                return "督促在规定时间内整改";
            }
        }

        // 其他隐患
//        if (otherDTO != null && "限期整改".equals(otherDTO.getRectificationDate())) {
//            return "督促在规定时间内整改";
//        }

        return "现场督促整改";
    }

    /**
     * 获取整改推进情况
     * @param fieldDTO
     * @return
     */
    public static String getCondition(SafetyCheckDTO fieldDTO) {

        List<RectifyDTO> recordsDTO = Optional.ofNullable(fieldDTO.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
        List<RectifyDTO> bottledDTO = Optional.ofNullable(fieldDTO.getBottledGasProblemArray()).orElse(Lists.newArrayList());
        OtherHiddenDangersDTO otherDTO = fieldDTO.getOtherHiddenDangers();

        // 消防安全隐患
        for (int i = 0; i < recordsDTO.size(); i ++) {
            RectifyDTO rectifyDTO = recordsDTO.get(i);
            if ("限期整改".equals(rectifyDTO.getRectificationDate())) {
                return "定期检查";
            }
            if ("现场整改".equals(rectifyDTO.getRectificationDate())) {
                return "已完成";
            }
        }

        // 瓶装燃气隐患
        for (int i = 0; i < bottledDTO.size(); i ++) {

            // 重复问题不显示
            i ++;
            if (notShow(i)) continue;

            RectifyDTO rectifyDTO = bottledDTO.get(i);
            if ("限期整改".equals(rectifyDTO.getRectificationDate())) {
                return "定期检查";
            }
            if ("现场整改".equals(rectifyDTO.getRectificationDate())) {
                return "已完成";
            }
        }

        // 其他隐患
        if (otherDTO != null) {
            return "已完成";
        }

        return "";
    }

//    public static String getCondition(SafetyCheckDTO fieldDTO, List<SafetyCheckDTO> safetyCheckDTOList) {
//        // 获取离这次查询最近的下一次查询
//        SafetyCheckDTO lastSafetyCheck = null;
//        for (SafetyCheckDTO safetyCheckDTO : safetyCheckDTOList) {
//            if (fieldDTO.getPlaceName().equals(safetyCheckDTO.getPlaceName()) &&
//                    fieldDTO.getAddress().equals(safetyCheckDTO.getAddress()) &&
//                    fieldDTO.getInspectionDate().getTime() < safetyCheckDTO.getInspectionDate().getTime()) {
//                // 由于safetyCheckDTOList是按照升序查询排好序的，所以取到的第一条数据就是需要的数据
//                lastSafetyCheck = safetyCheckDTO;
//                break;
//            }
//        }
//
//        if (lastSafetyCheck == null) {
//            String value = getMeasure(fieldDTO);
//            if ("督促在规定时间内整改".equals(value)) {
//                return "定期检查";
//            } else {
//                return "已完成";
//            }
//        }
//
//        // 最近的下一次
//        List<RectifyDTO> lastRecordsDTO = Optional.ofNullable(lastSafetyCheck.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
//        List<RectifyDTO> lastBottledDTO = Optional.ofNullable(lastSafetyCheck.getBottledGasProblemArray()).orElse(Lists.newArrayList());
//        OtherHiddenDangersDTO lastOtherDTO = lastSafetyCheck.getOtherHiddenDangers();
//
//        // 本次
//        List<RectifyDTO> recordsDTO = Optional.ofNullable(fieldDTO.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
//        List<RectifyDTO> bottledDTO = Optional.ofNullable(fieldDTO.getBottledGasProblemArray()).orElse(Lists.newArrayList());
//        OtherHiddenDangersDTO otherDTO = fieldDTO.getOtherHiddenDangers();
//
//        // 消防安全隐患
//        for (int i = 0; i < recordsDTO.size(); i ++) {
//            RectifyDTO rectifyDTO = recordsDTO.get(i);
//            RectifyDTO lastRectifyDTO = lastRecordsDTO.get(i);
//            if ("限期整改".equals(rectifyDTO.getRectificationDate()) && "限期整改".equals(lastRectifyDTO.getRectificationDate())) {
//                return "定期检查";
//            }
//        }
//
//        // 瓶装燃气隐患
//        for (int i = 0; i < bottledDTO.size(); i ++) {
//            RectifyDTO rectifyDTO = bottledDTO.get(i);
//            RectifyDTO lastRectifyDTO = lastBottledDTO.get(i);
//            if ("限期整改".equals(rectifyDTO.getRectificationDate()) && "限期整改".equals(lastRectifyDTO.getRectificationDate())) {
//                return "定期检查";
//            }
//        }
//
//        // 其他隐患
//        if (otherDTO != null && "限期整改".equals(otherDTO.getRectificationDate()) && "限期整改".equals(lastOtherDTO.getRectificationDate())) {
//            return "定期检查";
//        }
//
//        return "已完成";
//    }

    /**
     * 获取整改前图片
     * @param fieldDTO
     * @return
     */
    public static List<String> getPicturesBeforeRectification(SafetyCheckDTO fieldDTO) {
        List<String> list = new ArrayList<>();

        List<RectifyDTO> recordsDTO = Optional.ofNullable(fieldDTO.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
        List<RectifyDTO> bottledDTO = Optional.ofNullable(fieldDTO.getBottledGasProblemArray()).orElse(Lists.newArrayList());
        OtherHiddenDangersDTO otherDTO = fieldDTO.getOtherHiddenDangers();

        // 消防安全隐患
        for (RectifyDTO rectifyDTO : recordsDTO) {
            String urls = rectifyDTO.getPicturesBeforeRectification();
            if (StringUtils.isNotBlank(urls)) {
                list.addAll(Arrays.asList(urls.split(",")));
            }
        }

        // 瓶装燃气隐患
        int i = 0;
        for (RectifyDTO rectifyDTO : bottledDTO) {

            // 重复问题不显示
            i ++;
            if (notShow(i)) continue;

            String urls = rectifyDTO.getPicturesBeforeRectification();
            if (StringUtils.isNotBlank(urls)) {
                list.addAll(Arrays.asList(urls.split(",")));
            }
        }

        // 其他隐患
        if (otherDTO != null && StringUtils.isNotBlank(otherDTO.getPicturesBeforeRectification())) {
            list.addAll(Arrays.asList(otherDTO.getPicturesBeforeRectification().split(",")));
        }

        // 老数据图片
        RectifyDTO oldImg = fieldDTO.getOldImg();
        if (oldImg != null && StringUtils.isNotBlank(oldImg.getPicturesBeforeRectification())) {
            list.addAll(Arrays.asList(oldImg.getPicturesBeforeRectification().split(",")));
        }

        return list;
    }

    /**
     * 获取整改后图片
     * @param fieldDTO
     * @return
     */
    public static List<String> getPicturesAfterRectification(SafetyCheckDTO fieldDTO) {
        List<String> list = new ArrayList<>();

        List<RectifyDTO> recordsDTO = Optional.ofNullable(fieldDTO.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
        List<RectifyDTO> bottledDTO = Optional.ofNullable(fieldDTO.getBottledGasProblemArray()).orElse(Lists.newArrayList());
        OtherHiddenDangersDTO otherDTO = fieldDTO.getOtherHiddenDangers();

        // 老数据图片
        RectifyDTO oldImg = fieldDTO.getOldImg();
        if (oldImg != null && StringUtils.isNotBlank(oldImg.getPicturesAfterRectification())) {
            list.addAll(Arrays.asList(oldImg.getPicturesAfterRectification().split(",")));
        }

        // 消防安全隐患
        for (RectifyDTO rectifyDTO : recordsDTO) {
            String urls = rectifyDTO.getPicturesAfterRectification();
            if (StringUtils.isNotBlank(urls)) {
                list.addAll(Arrays.asList(urls.split(",")));
            }
        }
        // 瓶装燃气隐患
        int i = 0;
        for (RectifyDTO rectifyDTO : bottledDTO) {

            // 重复问题不显示
            i ++;
            if (notShow(i)) continue;

            String urls = rectifyDTO.getPicturesAfterRectification();
            if (StringUtils.isNotBlank(urls)) {
                list.addAll(Arrays.asList(urls.split(",")));
            }
        }
        // 其他隐患
        if (otherDTO != null && StringUtils.isNotBlank(otherDTO.getPicturesAfterRectification())) {
            list.addAll(Arrays.asList(otherDTO.getPicturesAfterRectification().split(",")));
        }

        return list;
    }

    /**
     * 设置隐患信息
     * @param dto
     * @param lastList
     * @param imgNo
     * @return
     */
    public static List<Map<String, Object>> getHiddenDangerInfo(SafetyCheckDTO dto, List<SafetyCheckDTO> lastList, int imgNo) {
        List<Map<String, Object>> mapList = new ArrayList<>();

        List<RectifyDTO> recordsDTO = Optional.ofNullable(dto.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
        List<RectifyDTO> bottledDTO = Optional.ofNullable(dto.getBottledGasProblemArray()).orElse(Lists.newArrayList());
        OtherHiddenDangersDTO otherDTO = dto.getOtherHiddenDangers();

        // 老数据图片
        RectifyDTO oldImg = dto.getOldImg();

        // 消防安全隐患
        for (RectifyDTO rectifyDTO : recordsDTO) {

            if (rectifyDTO.getRectificationDate() != null && !"已整改".equals(rectifyDTO.getRectificationDate())) {
                // 如果前一条某个问题存在隐患，就不再次显示该问题
                if (isPreviousHidden(dto, rectifyDTO, lastList, 1)) continue;

                Map<String, Object> map = new HashMap<>();
                map.put("hidden", rectifyDTO.getTitle());
                String type = rectifyDTO.getRectificationDate();
                map.put("measure", ("限期整改".equals(type)?"督促在规定时间内整改":"现场督促整改"));
                // 设置整改前图片
                beforeImg(map, rectifyDTO, oldImg, imgNo);
                // 设置整改推进情况和整改后图片
                setConditionAndAfterImg(map, dto, rectifyDTO, oldImg, lastList, 1, 1);

                mapList.add(map);
            }
        }
        // 瓶装燃气隐患
        int i = 0;
        for (RectifyDTO rectifyDTO : bottledDTO) {

            // 重复问题不显示
            i ++;
            if (notShow(i)) continue;

            if (rectifyDTO.getRectificationDate() != null && !"已整改".equals(rectifyDTO.getRectificationDate())) {
                // 如果前一条某个问题存在隐患，就不再次显示该问题
                if (isPreviousHidden(dto, rectifyDTO, lastList, 2)) continue;

                Map<String, Object> map = new HashMap<>();
                map.put("hidden", rectifyDTO.getTitle());
                String type = rectifyDTO.getRectificationDate();
                map.put("measure", ("限期整改".equals(type)?"督促在规定时间内整改":"现场督促整改"));
                // 设置整改前图片
                beforeImg(map, rectifyDTO, oldImg, imgNo);
                // 设置整改推进情况和整改后图片
                setConditionAndAfterImg(map, dto, rectifyDTO, oldImg, lastList, 2, 1);

                mapList.add(map);
            }
        }
        // 其他隐患
        if (otherDTO != null &&  StringUtils.isNotBlank(otherDTO.getKey())) {
            Map<String, Object> map = new HashMap<>();
            map.put("hidden", otherDTO.getKey());
            map.put("measure", "现场督促整改");
            map.put("condition", "已完成");

            map.put("beforeImg", PictureUtils.splitUrl(StringUtils.isBlank(otherDTO.getPicturesBeforeRectification())?
                    Arrays.asList():Arrays.asList(otherDTO.getPicturesBeforeRectification().split(",")), imgNo));
            if (oldImg != null && StringUtils.isNotBlank(oldImg.getPicturesBeforeRectification())) {
                map.put("beforeImg", PictureUtils.splitUrl(StringUtils.isBlank(oldImg.getPicturesBeforeRectification())?Arrays.asList():
                        Arrays.asList(oldImg.getPicturesBeforeRectification().split(",")), imgNo));
            }

            map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(otherDTO.getPicturesAfterRectification())?
                    Arrays.asList():Arrays.asList(otherDTO.getPicturesAfterRectification().split(",")), imgNo));
            if (oldImg != null && StringUtils.isNotBlank(oldImg.getPicturesAfterRectification())) {
                map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(oldImg.getPicturesAfterRectification())?Arrays.asList():
                        Arrays.asList(oldImg.getPicturesBeforeRectification().split(",")), imgNo));
            }

            mapList.add(map);
        }

        return mapList;
    }

    /**
     * 设置整改前图片
     * @param map
     * @param rectifyDTO
     * @param oldImg
     * @param imgNo
     */
    public static void beforeImg(Map<String, Object> map, RectifyDTO rectifyDTO, RectifyDTO oldImg, int imgNo) {
        String beforeImg = rectifyDTO.getPicturesBeforeRectification();
        map.put("beforeImg", PictureUtils.splitUrl(StringUtils.isBlank(beforeImg)?Arrays.asList():
                Arrays.asList(beforeImg.split(",")), imgNo));
        if (oldImg != null && StringUtils.isNotBlank(oldImg.getPicturesBeforeRectification())) {
            map.put("beforeImg", PictureUtils.splitUrl(StringUtils.isBlank(oldImg.getPicturesBeforeRectification())?Arrays.asList():
                    Arrays.asList(oldImg.getPicturesBeforeRectification().split(",")), imgNo));
        }
    }

    /**
     * 设置整改后图片
     * @param map
     * @param rectifyDTO
     * @param oldImg
     * @param lastDto
     * @param lastR
     * @param imgNo
     */
    public static void afterImg(Map<String, Object> map, RectifyDTO rectifyDTO, RectifyDTO oldImg,
                                SafetyCheckDTO lastDto, List<RectifyDTO> lastR, int imgNo) {
        String afterImg = rectifyDTO.getPicturesAfterRectification();
        if (lastR == null || lastR.size() == 0) {
            map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(afterImg)?Arrays.asList():
                    Arrays.asList(afterImg.split(",")), imgNo));
            if (oldImg != null && StringUtils.isNotBlank(oldImg.getPicturesAfterRectification())) {
                map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(oldImg.getPicturesAfterRectification())?
                        Arrays.asList():Arrays.asList(oldImg.getPicturesBeforeRectification().split(",")), imgNo));
            }
        } else {
            for (RectifyDTO last : lastR) {
                String lastImg = last.getPicturesAfterRectification();
                if (rectifyDTO.getTitle().equals(last.getTitle())) {
                    map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(lastImg)?Arrays.asList():
                            Arrays.asList(lastImg.split(",")), imgNo));
                    RectifyDTO lastOldImg = lastDto.getOldImg();
                    if (lastOldImg != null && StringUtils.isNotBlank(lastOldImg.getPicturesAfterRectification())) {
                        map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(lastOldImg.getPicturesAfterRectification())?Arrays.asList():
                                Arrays.asList(lastOldImg.getPicturesBeforeRectification().split(",")), imgNo));
                    }
                    break;
                }
            }
        }
    }

    /**
     * 获取后面一条数据
     * @param dto
     * @param allList 顺序为升序
     * @return
     */
    public static SafetyCheckDTO getNext(SafetyCheckDTO dto, List<SafetyCheckDTO> allList) {
        for (SafetyCheckDTO safetyCheckDTO : allList) {
            if (dto.getPlaceName().equals(safetyCheckDTO.getPlaceName()) &&
                    dto.getAddress().equals(safetyCheckDTO.getAddress()) &&
                    dto.getInspectionDate().getTime() < safetyCheckDTO.getInspectionDate().getTime()) {
                // 由于safetyCheckDTOList是按照升序查询排好序的，所以取到的第一条数据就是需要的数据
                return safetyCheckDTO;
            }
        }
        return null;
    }

    /**
     * 设置整改推进情况和整改后图片
     * @param map
     * @param dto
     * @param rectifyDTO
     * @param oldImg
     * @param allList
     * @param type
     * @param imgNo
     */
    public static List<String> setConditionAndAfterImg(Map<String, Object> map, SafetyCheckDTO dto, RectifyDTO rectifyDTO, RectifyDTO oldImg,
                                         List<SafetyCheckDTO> allList, int type, int imgNo) {
        List<String> imgList = new ArrayList<>();

        for (SafetyCheckDTO safetyCheckDTO : allList) {
            if (dto.getPlaceName().equals(safetyCheckDTO.getPlaceName()) &&
                    dto.getAddress().equals(safetyCheckDTO.getAddress()) &&
                    dto.getInspectionDate().getTime() < safetyCheckDTO.getInspectionDate().getTime()) {
                if (type == 1) {
                   List<RectifyDTO> rectifyDTOList = safetyCheckDTO.getArrayOfFireSafetyPatrolRecords();
                   if (rectifyDTOList != null) {
                       for (RectifyDTO next : rectifyDTOList) {
                           if (next.getTitle().equals(rectifyDTO.getTitle()) && "限期整改".equals(rectifyDTO.getRectificationDate()) && !"限期整改".equals(next.getRectificationDate())) {
                               map.put("condition", "已完成");

                               if (oldImg != null && StringUtils.isNotBlank(oldImg.getPicturesAfterRectification())) {
                                   map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(oldImg.getPicturesAfterRectification()) ?
                                           Arrays.asList() : Arrays.asList(oldImg.getPicturesBeforeRectification().split(",")), imgNo));
                               }
                               String afterImg = next.getPicturesAfterRectification();
                               map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(afterImg) ? Arrays.asList() :
                                       Arrays.asList(afterImg.split(",")), imgNo));

                               imgList.addAll(StringUtils.isBlank(afterImg) ? Arrays.asList() : Arrays.asList(afterImg.split(",")));
                               return imgList;
                           }
                       }
                   }
                }
                if (type == 2) {
                    List<RectifyDTO> rectifyDTOList = safetyCheckDTO.getBottledGasProblemArray();
                    if (rectifyDTOList != null) {
                        int i = 0;
                        for (RectifyDTO next : rectifyDTOList) {

                            // 重复问题不显示
                            i ++;
                            if (notShow(i)) continue;

                            if (next.getTitle().equals(rectifyDTO.getTitle()) && "限期整改".equals(rectifyDTO.getRectificationDate()) && !"限期整改".equals(next.getRectificationDate())) {
                                map.put("condition", "已完成");

                                if (oldImg != null && StringUtils.isNotBlank(oldImg.getPicturesAfterRectification())) {
                                    map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(oldImg.getPicturesAfterRectification()) ?
                                            Arrays.asList() : Arrays.asList(oldImg.getPicturesBeforeRectification().split(",")), imgNo));
                                }
                                String afterImg = next.getPicturesAfterRectification();
                                map.put("afterImg", PictureUtils.splitUrl(StringUtils.isBlank(afterImg) ? Arrays.asList() :
                                        Arrays.asList(afterImg.split(",")), imgNo));

                                imgList.addAll(StringUtils.isBlank(afterImg) ? Arrays.asList() : Arrays.asList(afterImg.split(",")));
                                return imgList;
                            }
                        }
                    }
                }
            }
        }
        List<String> img = StringUtils.isBlank(rectifyDTO.getPicturesAfterRectification())?Arrays.asList():
                Arrays.asList(rectifyDTO.getPicturesAfterRectification().split(","));
        map.put("afterImg", PictureUtils.splitUrl(img, imgNo));
        map.put("condition", "限期整改".equals(rectifyDTO.getRectificationDate())?"定期检查":"已完成");

        imgList.addAll(img);
        return imgList;
    }

    /**
     * 获取前面一条数据
     * @param dto
     * @param allList 顺序为升序
     * @return
     */
    public static SafetyCheckDTO getPrevious(SafetyCheckDTO dto, List<SafetyCheckDTO> allList) {
        // reversed() 表示倒序的意思，如果不使用此方法则是正序。
        allList = allList.stream().sorted(Comparator.comparing(SafetyCheckDTO::getInspectionDate).reversed()).collect(Collectors.toList());
        for (SafetyCheckDTO safetyCheckDTO : allList) {
            if (dto.getPlaceName().equals(safetyCheckDTO.getPlaceName()) &&
                    dto.getAddress().equals(safetyCheckDTO.getAddress()) &&
                    dto.getInspectionDate().getTime() > safetyCheckDTO.getInspectionDate().getTime()) {
                return safetyCheckDTO;
            }
        }
        return null;
    }

    /**
     * 判断前一条是否为隐患
     * @param dto
     * @param allList
     * @param type 1为消防，2为瓶装
     * @return
     */
    public static boolean isPreviousHidden(SafetyCheckDTO dto, RectifyDTO rectifyDTO, List<SafetyCheckDTO> allList, int type) {
        // 获取前面一条数据
        SafetyCheckDTO pDto = getPrevious(dto, allList);
        List<RectifyDTO> pRecords = Arrays.asList();
        List<RectifyDTO> pBottled = Arrays.asList();
        if (pDto != null) {
            pRecords = Optional.ofNullable(pDto.getArrayOfFireSafetyPatrolRecords()).orElse(Lists.newArrayList());
            pBottled = Optional.ofNullable(pDto.getBottledGasProblemArray()).orElse(Lists.newArrayList());
        }
        if (type == 1) {
            for (RectifyDTO r : pRecords) {
                if (r.getTitle().equals(rectifyDTO.getTitle()) && "限期整改".equals(r.getRectificationDate())) {
                    return true;
                }
            }
        }
        if (type == 2) {
            for (RectifyDTO r : pBottled) {
                if (r.getTitle().equals(rectifyDTO.getTitle()) && "限期整改".equals(r.getRectificationDate())) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 设置页脚
     * @param commonParam
     * @return
     */
    public static Map<String, Object> getFooter(CommonParam commonParam) {
        String str = "居委会";
        return Map.of("footer", UNIT_NAME.equals(commonParam.getUnitName()) ? "威清门应急服务中心" : commonParam.getCommunity() + str);
    }

    public static Map<String, Object> getFooter(Sys_user commonParam) {
        String str = "居委会";
        return Map.of("footer", UNIT_NAME.equals(commonParam.getUnitName()) ? "威清门应急服务中心" : commonParam.getCommunity() + str);
    }

    /**
     * 门头照（三合一专用）
     *
     * @param fieldDTO
     * @return
     */
    public static boolean setThreeInOnePicture(SafetyCheckDTO fieldDTO, Map<String, Object> dataMap) {
        //门头照
        String door_title = "附件：{} {} 门头照、三合一照片";
        door_title = StrFormatter.format(door_title, fieldDTO.getPlaceName(),
                DateUtil.format(fieldDTO.getInspectionDate(), "yyyy-MM-dd"));
        List<Map> door_pictures = new ArrayList<>();

        // 门头照
        String inspectionPhotos = fieldDTO.getInspectionPhotos();
        if (!StrUtil.isBlank(inspectionPhotos)) {
            String[] door_picture = inspectionPhotos.split(",");
            for (String url : door_picture) {
                if (!StrUtil.isBlank(url)) {
                    Map<String, Object> pictureMap = Maps.newHashMap();
                    pictureMap.put("picture", PictureUtils.scaleImage(url, 180, false));
                    door_pictures.add(pictureMap);
                    break;
                }
            }
        }

        // 三合一照片
        String threeInOnePhoto = fieldDTO.getThreeInOnePhoto();
        if (!StrUtil.isBlank(threeInOnePhoto)) {
            String[] door_picture = threeInOnePhoto.split(",");
            int i = 0;
            for (String url : door_picture) {
                if (!StrUtil.isBlank(url) && i < 2) {
                    i ++;
                    Map<String, Object> pictureMap = Maps.newHashMap();
                    pictureMap.put("picture", PictureUtils.scaleImage(url, 180, false));
                    door_pictures.add(pictureMap);
                }
            }
        }

        dataMap.put("door_title", door_pictures.size() == 0 ? "" : door_title);
        dataMap.put("door_pictures", door_pictures);
        return door_pictures.size() == 0 ? false : true;
    }

    /**
     * 设置门头照(除危房外)
     *
     * @param fieldDTO
     * @return
     */
    public static boolean setDoorPicture(SafetyCheckDTO fieldDTO, Map<String, Object> dataMap) {
        //门头照
        String door_title = "附件：{} {} 门头照";
        door_title = StrFormatter.format(door_title, fieldDTO.getPlaceName(),
                DateUtil.format(fieldDTO.getInspectionDate(), "yyyy-MM-dd"));
        List<Map> door_pictures = new ArrayList<>();
        String inspectionPhotos = fieldDTO.getInspectionPhotos();
        if (!StrUtil.isBlank(inspectionPhotos)) {
            String[] door_picture = inspectionPhotos.split(",");
            for (String url : door_picture) {
                if (!StrUtil.isBlank(url)) {
                    Map<String, Object> pictureMap = Maps.newHashMap();
                    pictureMap.put("picture", PictureUtils.scaleImage(url, 240, false));
                    door_pictures.add(pictureMap);
                }
            }
        }
        dataMap.put("door_title", door_pictures.size() == 0 ? "" : door_title);
        dataMap.put("door_pictures", door_pictures);
        return door_pictures.size() == 0 ? false : true;
    }

    /**
     * 获取门头照(危房专用)
     *
     * @param fieldDTO
     * @return
     */
    public static List<Map> getDoorPicture(SafetyCheckDTO fieldDTO) {
        // 早
        String dilapidatedHousePhotoEarly = fieldDTO.getDilapidatedHousePhotoEarly();
        // 中
        String dilapidatedHouseInPhoto = fieldDTO.getDilapidatedHouseInPhoto();
        // 晚
        String dangerousHousePhotoLate = fieldDTO.getDangerousHousePhotoLate();

        if (StringUtils.isBlank(dilapidatedHousePhotoEarly) && StringUtils.isBlank(dilapidatedHouseInPhoto) &&
                StringUtils.isBlank(dangerousHousePhotoLate)) {
            return new ArrayList<>();
        }

        List<Map> pictures = new ArrayList<>();
        String[] morning = StringUtils.isBlank(dilapidatedHousePhotoEarly) ? new String[0] : dilapidatedHousePhotoEarly.split(",");
        String[] noon = StringUtils.isBlank(dilapidatedHouseInPhoto) ? new String[0] : dilapidatedHouseInPhoto.split(",");
        String[] night = StringUtils.isBlank(dangerousHousePhotoLate) ? new String[0] : dangerousHousePhotoLate.split(",");
        for (String url : morning) {
            Map<String, Object> pictureMap = Maps.newHashMap();
            pictureMap.put("picture", PictureUtils.scaleImage(url, 180, true));
            pictures.add(pictureMap);
        }
        for (String url : noon) {
            Map<String, Object> pictureMap = Maps.newHashMap();
            pictureMap.put("picture", PictureUtils.scaleImage(url, 180, true));
            pictures.add(pictureMap);
        }
        for (String url : night) {
            Map<String, Object> pictureMap = Maps.newHashMap();
            pictureMap.put("picture", PictureUtils.scaleImage(url, 180, true));
            pictures.add(pictureMap);
        }
        return pictures;
    }

    /**
     * 判断消防和瓶装重复问题是否显示
     * 消防安全巡查记录: 1 2 5 6 7 14 => 瓶装燃气用户安全管理检查表：8 12 23 20 13 10  重复
     * 所以瓶装的这些问题不显示
     *
     * @param index
     * @return
     */
    public static boolean notShow(int index) {
        List<Integer> indexList = List.of(8, 12, 23, 20, 13, 10);
        if (indexList.contains(index)) {
            return true;
        } else {
            return false;
        }
    }
}
